package com.zy.yun.controller.sys;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.yun.base.annotation.NotNullPara;
import com.zy.yun.base.common.DataTable;
import com.zy.yun.base.common.LTree;
import com.zy.yun.base.common.RestResult;
import com.zy.yun.base.constant.StatusEnum;
import com.zy.yun.base.entity.Res;
import com.zy.yun.base.entity.RoleOrganization;
import com.zy.yun.base.entity.RoleRes;
import com.zy.yun.base.entity.dto.OrganizationDTO;
import com.zy.yun.provider.service.IOrganizationService;
import com.zy.yun.base.entity.Organization;
import com.zy.yun.base.entity.vo.OrganizationVO;
import com.zy.yun.provider.service.IRoleOrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zy.yun.controller.common.BaseController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 组织管理表 前端控制器
 * </p>
 *
 * @author 王彦委
 * @since 2019-10-21
 */
@RestController
@RequestMapping("/organization")
@Api(tags = "组织管理", description = "组织管理")
public class OrganizationController extends BaseController<Organization, OrganizationVO> {


    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IRoleOrganizationService roleOrganizationService;

    /**
     * 功能描述: 获取组织信息
     *
     * @auther: wangyanwei
     * @date: 2019/9/21 10:45
     * @param:
     * @return:
     */
    @ApiOperation("获取组织信息")
    @PostMapping(value = "getOrganizationTree", name = "获取组织信息")
    public RestResult getOrganizationTree(@RequestParam("nodeIds") List<Long> nodeIds) {

        EntityWrapper<Organization> queryWrapper = new EntityWrapper<Organization>();
        queryWrapper.isNull("pid");
        List<Organization> resList = organizationService.selectList(queryWrapper);
        List<LTree> lTrees = getLTrees(resList, nodeIds);

        return RestResult.buildSuccess(lTrees);
    }

    /**
     * 功能描述: 查询子项
     *
     * @auther: wangyanwei
     * @date: 2019/9/22 13:28
     * @param:
     * @return:
     */
    private List<LTree> getLTrees(List<Organization> organizationList, List<Long> nodeIds) {
        List<LTree> lTrees = new ArrayList<>();

        for (Organization organization : organizationList) {
            //拼装成组织树
            LTree lTree = new LTree();
            lTree.setId(organization.getId());
            lTree.setTitle(organization.getName());
            if (nodeIds.contains(organization.getId())) {
                lTree.setSpread(true);
            }
            EntityWrapper<Organization> queryWrapper = new EntityWrapper<Organization>();
            queryWrapper.eq("pid", organization.getId());
            List<Organization> list = organizationService.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                lTrees.add(lTree);
                continue;
            }
            //递归获取子项
            lTree.setChildren(getLTrees(list, nodeIds));
            lTrees.add(lTree);
        }
        return lTrees;
    }

    /**
     * @Author: 王彦委
     * @Description: 组织列表
     * @Date: 21:38 2019/10/21
     */
    @PostMapping("findPage")
    public DataTable findPage(OrganizationDTO organization, @RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "30") Integer pageSize) {

        EntityWrapper<Organization> organizationQueryWrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(organization.getStatus())) {
            organizationQueryWrapper.eq("status", organization.getStatus());
        }
        if (StringUtils.isNotBlank(organization.getName())) {
            organizationQueryWrapper.like("name", organization.getName());
        }

        if (null == organization.getPid()) {
            organizationQueryWrapper.isNull("pid");
        } else {
            organizationQueryWrapper.eq("pid", organization.getPid());

        }


        return findPage(organizationQueryWrapper, pageNum, pageSize);

    }

    /**
     * @Author: 王彦委
     * @Description: 增加组织
     * @Date: 21:57 2019/10/21
     */
    @ApiOperation("增加组织")
    @PostMapping("save")
    public RestResult save(@RequestParam(defaultValue = "0") Long pid, OrganizationDTO organization) {

        organization.setStatus(StatusEnum.STATUS_START.getCode());
        organization.setCreateTime(new Date());
        if (organizationService.insert(organization)) {
            return RestResult.buildSuccess();
        }

        return RestResult.buildError();
    }


    /**
     * @Author: 王彦委
     * @Description: 批量删除组织
     * @Date: 22:14 2019/10/21
     */
    @ApiOperation("批量删除组织")
    @PostMapping("batchDeleteOrganization")
    public RestResult batchDeleteOrganization(@RequestParam("ids") List<Long> ids) {

        //判断是否有子菜单
        EntityWrapper<Organization> organizationQueryWrapper = new EntityWrapper<>();
        organizationQueryWrapper.in("pid", ids);
        List<Organization> list = organizationService.selectList(organizationQueryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return RestResult.buildError("请先删除组织下的节点！");
        }

        if (organizationService.deleteBatchIds(ids)) {
            return RestResult.buildSuccess();
        }
        return RestResult.buildError();

    }




    /**
     * @Author: 王彦委
     * @Description: 查询分配的数据权限的资源
     * @Date: 21:27 2019/10/20
     */
    @ApiOperation("查询分配权限的资源")
    @PostMapping("getAuthOrganizationTree")
    @NotNullPara({"roleId"})
    public RestResult getAuthOrganizationTree(Long roleId) {

        //1：查询所有开启的组织
        EntityWrapper<Organization> resQueryWrapper = new EntityWrapper<>();
        resQueryWrapper.eq("status", StatusEnum.STATUS_START.getCode());
        resQueryWrapper.isNull("pid");
        List<Organization> list = organizationService.selectList(resQueryWrapper);

        //2: 查询本角色拥有的组织
        EntityWrapper<RoleOrganization> roleResQueryWrapper = new EntityWrapper<>();
        roleResQueryWrapper.eq("roleId", roleId);
        List<RoleOrganization> roleResList = roleOrganizationService.selectList(roleResQueryWrapper);
        List<LTree> resLTrees = getOrganizationLTrees(list, roleResList);

        return RestResult.buildSuccess(resLTrees);
    }


    /**
     * @Author: 王彦委
     * @Description: 查询子资源
     * @Date: 21:35 2019/10/20
     */
    private List<LTree> getOrganizationLTrees(List<Organization> resList, List<RoleOrganization> roleResList) {
        List<LTree> lTrees = new ArrayList<>();

        for (Organization res : resList) {
            LTree lTree = new LTree();
            lTree.setId(res.getId());
            lTree.setTitle(res.getName());
            lTree.setChecked(false);
            EntityWrapper<Organization> queryWrapper = new EntityWrapper<Organization>();
            queryWrapper.eq("pid", res.getId());
            queryWrapper.eq("status", StatusEnum.STATUS_START.getCode());
            List<Organization> list = organizationService.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                //只把最后一级设置成选中
                for (RoleOrganization roleRes : roleResList) {
                    if (res.getId().equals(roleRes.getOrganizationId())) {
                        System.err.println("resId=" + res.getId() + " roleResId=" + roleRes.getOrganizationId());
                        lTree.setChecked(true);
                    }
                }
                lTrees.add(lTree);
                continue;
            }
            lTree.setChildren(getOrganizationLTrees(list, roleResList));
            lTrees.add(lTree);
        }
        return lTrees;
    }


}
